<template>
    <div class="cinema-list-map">
        <van-nav-bar
            :title="$t('m.Map')"
            left-arrow
            @click-left="$router.back(-1)"
        />
        <gmap-map
            :center="center"
            :zoom="11"
            :options="mapControls"
            :style="mapStyle"
            v-show="loadingData"
            ref="map"
        >
            <gmap-marker
                v-show="userMarkers.lat && userMarkers.lng"
                key="user-location"
                :position="userMarkers"
                :icon="userLocationIcon"
            ></gmap-marker>
            <gmap-marker
                :key="index"
                v-for="(m, index) in markers"
                :position="m.position"
                :icon="icon"
                @click="showInfoWin(m)"
            ></gmap-marker>
            <GmapInfoWindow
                :opened="infoWinOpen"
                :position="infoWindowPos"
                @closeclick="closeClick"
            >
                <div class="info-title" @click="goToDetail(infoWindowId)">
                    <div class="title-left g-font">{{infoWindowName}}</div>
                    <div class="title-right"></div>
                </div>
                <div class="g-font" @click="goToDetail(infoWindowId)">{{infoWindowStreet}}</div>
                <div class="g-font" @click="goToDetail(infoWindowId)">{{infoWindowLocation}}</div>
            </GmapInfoWindow>
        </gmap-map>

    </div>
</template>
<script>
    import {searchCimenaList} from '../../static/api/mgc_api'
    import {gmapApi} from 'vue2-google-maps'
    import Qs from 'qs'
    import township from '../../static/json/township'
    import region from '../../static/json/region'
    import mm_region from '../../static/mmJson/region'
    import mm_township from '../../static/mmJson/township'
    export default {
        name: "GoogleMapByCinemaList",
        computed: {
            google: gmapApi
        },
        data() {
            return {
                responseData: [], // 后台返回的lines原始数据
                center: {lat: 16.869607, lng: 96.195590},
                markers: [],
                mapControls: {
                    disableDefaultUI: true,
                    zoomControl: true,
                },
                mapStyle: {
                    width: '100%',
                    height: '0',
                },
                popHeight: {
                    maxHeight: '0',
                },
                currentPlace: null,
                icon: {
                    url: '/static/img/images/cinema-pop.png',
                    scaledSize: {
                        width: 30,
                        height: 30,
                    },
                },
                loadingData: true,
                userMarkers: {lat: 0, lng: 0},
                userLocationIcon: {
                    path: 0,
                    fillColor: '#448AFF',
                    fillOpacity: 0.9,
                    scale: 6,
                    strokeColor: '#fff',
                    strokeOpacity: 0.9,
                    strokeWeight: 1
                },
                regionId: '',
                townshipId: '',
                infoWinOpen: false,
                infoWindowPos: null,
                infoWindowName: '',
                infoWindowStreet: '',
                infoWindowLocation: '',
                infoWindowId: '',

            };
        },
        computed: {
            regionJson() {
                if (this.$store.state.store.localLang == 'MM') {
                    return mm_region
                } else {
                    return region
                }
            },
            townshipJson() {
                if (this.$store.state.store.localLang == 'MM') {
                    return mm_township
                } else {
                    return township
                }
            },
        },
        methods: {
            getTownshipType (t) {
                let str = ''
                this.townshipJson.forEach((item) => {
                    if (item.value == t) {
                        str = item.text || ''
                    }
                })
                return str
            },
            getRegionTypeStr(t) {
                let str = ''
                this.regionJson.forEach((item) => {
                    if (item.value == t) {
                        str = item.text || ''
                    }
                })
                return str
            },
            closeClick() {
                this.infoWinOpen = false;
                return false;
            },
            showInfoWin(val) {
                this.infoWindowPos = val.position;
                this.infoWindowId = val.info.id;
                this.infoWindowName = this.getCinemaName(val.info);
                this.infoWindowStreet = this.getStreetName(val.info);
                this.infoWindowLocation = this.getTownshipType(val.info.townshipId) + ',' +this.getRegionTypeStr(val.info.regionId);
                this.infoWinOpen = true;
            },
            goToDetail(id) {
                this.$router.push({
                    path:'/movie/cinema-detail',
                    query:{
                        id: id
                    }
                })
            },

            getList(pageNum) {
                if (pageNum == 1) {
                    this.pageData.pageNum = 1;
                }

                let searchForm = {};
                searchForm.regionId = this.regionId
                searchForm.townshipId = this.townshipId
                let params = Qs.stringify(searchForm, {arrayFormat: 'repeat'})
                searchCimenaList(params).then((res) => {
                    if (res.data.data.errorID == 0) {
                        let  cinemaArr = res.data.data.object.info || []
                        const bounds = new google.maps.LatLngBounds()
                        for (let i=0;i<cinemaArr.length;i++){
                            let _o = {
                                lat : Number(cinemaArr[i].latitude),
                                lng : Number(cinemaArr[i].longitude),
                            };
                            let _i = {
                                id: cinemaArr[i].id,
                                name: cinemaArr[i].name,
                                nameBurmese: cinemaArr[i].nameBurmese,
                                street: cinemaArr[i].street,
                                streetBurmese: cinemaArr[i].streetBurmese,
                                regionId: cinemaArr[i].regionId,
                                townshipId: cinemaArr[i].townshipId
                            };
                            let markersInfo = {
                                position: _o,
                                info: _i
                            };
                            bounds.extend(_o)
                            this.markers.push(markersInfo);
                        }
                        console.log(this.markers,'this.markers')
                        this.$refs.map.fitBounds(bounds)
                        this.finished = true
                        this.loading = false
                        this.$nextTick(() => {
                            this.$refs.map.$mapPromise.then((map) => {
                                this.loadingData = true; // 不能v-show='loadingData = false' this.$refs.map.fitBound不生效，或者导致rooms混乱
                                this.initDom(map)
                            })
                        })
                    } else {
                        this.$toast(res.data.data.message)
                        this.finished = true
                        this.loading = false
                    }

                }).catch((e) => {
                    console.log(e)
                    this.$toast('error, please try again later~')
                    this.finished = true
                    this.loading = false
                })
            },
            initDom(map){
                let controlDiv = document.createElement('div');

                let firstChild = document.createElement('button');
                firstChild.style.backgroundColor = '#fff';
                firstChild.style.border = 'none';
                firstChild.style.outline = 'none';
                firstChild.style.width = '28px';
                firstChild.style.height = '28px';
                firstChild.style.borderRadius = '2px';
                firstChild.style.boxShadow = '0 1px 4px rgba(0,0,0,0.3)';
                firstChild.style.cursor = 'pointer';
                firstChild.style.marginRight = '10px';
                firstChild.style.padding = '0px';
                firstChild.title = 'Your Location';
                controlDiv.appendChild(firstChild);

                let secondChild = document.createElement('div');
                secondChild.style.margin = '5px';
                secondChild.style.width = '18px';
                secondChild.style.height = '18px';
                secondChild.style.backgroundImage = 'url(https://maps.gstatic.com/tactile/mylocation/mylocation-sprite-1x.png)';
                secondChild.style.backgroundSize = '180px 18px';
                secondChild.style.backgroundPosition = '0px 0px';
                secondChild.style.backgroundRepeat = 'no-repeat';
                secondChild.id = 'you_location_img';
                firstChild.appendChild(secondChild);
                controlDiv.index = 1;
                google.maps.event.addListener(map, 'dragend', () => {
                    let doc = document.getElementById('you_location_img')
                    doc.style.backgroundPosition = '0px 0px'
                });
                firstChild.addEventListener('click', () => {
                    let doc = document.getElementById('you_location_img')
                    let imgX = '0';
                    let animationInterval = setInterval( () =>{
                        if(imgX == '-18') imgX = '0';
                        else imgX = '-18';
                        doc.style.backgroundPosition = imgX+'0px 0px'
                    }, 500);
                    if(navigator.geolocation) {
                        navigator.geolocation.getCurrentPosition( (position) => {
                            // let latlng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
                            let latlng = {lat: position.coords.latitude, lng: position.coords.longitude};
                            this.userMarkers = latlng;
                            map.setCenter(latlng);
                            clearInterval(animationInterval);
                            doc.style.backgroundPosition = '-144px 0px'
                        });
                    }
                    else{
                        clearInterval(animationInterval);
                        doc.style.backgroundPosition = imgX+'0px 0px'
                    }
                });
                map.controls[google.maps.ControlPosition.RIGHT_BOTTOM].push(controlDiv);
            },
            translateString(str) {
                if (!str) return ''
                return this.$translateLang(str, 'unicodeTozawgyi');
            },
            getCinemaName(item){
                if(this.$store.state.store.localLang == 'MM'){
                    return this.translateString(item.nameBurmese)
                } else{
                    return this.translateString(item.name)
                }
            },
            getStreetName(item){
                if(this.$store.state.store.localLang == 'MM'){
                    return this.translateString(item.streetBurmese)
                } else{
                    return this.translateString(item.street)
                }
            },
        },
        mounted() {
            this.mapStyle.height = document.body.clientHeight - 46 + 'px';
            if(this.$route.query.regionId) {
                this.regionId = this.$route.query.regionId || ''
            }
            if(this.$route.query.townshipId) {
                this.townshipId = this.$route.query.townshipId || ''
            }
            this.$nextTick(() => {
                this.$refs.map.$mapPromise.then(() => {
                    this.getList()
                })
            })

        },

        beforeRouteLeave (to, from, next) {
            // 导航离开该组件的对应路由时调用
            // 可以访问组件实例 `this`
            // console.log(to,'to')
            let leave = true;
            // if (this.busLineListShow) {
            //     this.busLineListShow = false
            //     leave = false
            // }
            // if (this.linesPopShow) {
            //     this.linesPopShow = false
            //     leave = false
            // }
            if (leave) {
                next()
            } else {
                next(false)
            }
        },
        beforeRouteUpdate (to, from, next) {
            // 导航离开该组件的对应路由时调用
            // 可以访问组件实例 `this`
            // console.log(to,'to')
            let leave = true;
            // if (this.busLineListShow) {
            //     this.busLineListShow = false
            //     leave = false
            // }
            // if (this.linesPopShow) {
            //     this.linesPopShow = false
            //     leave = false
            // }
            if (leave) {
                next()
            } else {
                next(false)
            }
        },

    };
</script>
<style>
    .cinema-list-map .van-nav-bar .van-icon{
        color: #C8C8C8;
        margin-right: 15px;
        font-size: 18px;
    }
</style>
<style scoped>
    .g-font {
        font-family: Zawgyi-One, 'Avenir', Helvetica, Arial, sans-serif!important;
    }
    .info-title{
        display: flex;
    }
    .info-title .title-left{
        color: #ff4181;
        flex: 1;
    }
    .info-title .title-right{
        width: 10px;
        margin-left: 15px;
        position: relative;
    }
    .info-title .title-right:before{
        content: "";
        position: absolute;
        border-top: 1px solid #000;
        border-right: 1px solid #000;
        width: 7px;
        height: 7px;
        top: 50%;
        left: 50%;
        margin-left: -5px;
        margin-top: -4px;
        transform: rotate(45deg);
    }
</style>
